package com.milo.coding.syncronized;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @Author milo
 * @Date 2021-01-29 16:52:04
 * @Description 竞争
 */
public class T0_MultiThreadAndUnsafe {

    private static int total = 0;
    private static Object object = new Object(); // synchronized 内置锁，隐式锁
    private static ReentrantLock lock = new ReentrantLock(); // 显示锁
    // 二者统都是互斥锁


    public static void main(String[] args) throws InterruptedException {

        // 线程工具类
        CountDownLatch countDownLatch = new CountDownLatch(1);

        for(int i=0;i<10;i++){
            new Thread(()->{
                try {
                    // 让所有的线程创建完毕后一起执行，更好的表现出并发
                    countDownLatch.await();
                    for(int j=0;j<1000;j++){
                        try {
                            // lock.lock();
                            // synchronized (object){
                                total++;
                            // }

                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            // lock.unlock();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        Thread.sleep(1000);

        // 让所有的线程开始执行
        countDownLatch.countDown();

        // 等待上面的线程执行
        Thread.sleep(2000);

        System.out.println(total);
    }
}
